package net.opentsdb.meta;

import com.stumbleupon.async.Callback;
import com.stumbleupon.async.Deferred;
import net.opentsdb.core.TSDB;
import org.hbase.async.GetRequest;
import org.hbase.async.KeyValue;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * @Author hujf
 * @Date 2022/2/28 15:06
 * @Description TODO
 */
public class TSMeta {

    public static final byte [] FAMILY = "name".getBytes(StandardCharsets.UTF_8);
    private static final byte[] META_QUALIFIER = "TE_META".getBytes(StandardCharsets.UTF_8);

    public static Deferred<Boolean> storeIfNecessary(TSDB tsdb,byte[] tsuid){
        final GetRequest get = new GetRequest(tsdb.metaTable(),tsuid);
        get.family(FAMILY);
        get.qualifier(META_QUALIFIER);

        final class CreateNewCB implements Callback<Deferred<Boolean>, Object>{

            @Override
            public Deferred<Boolean> call(Object arg) throws Exception {
                return null;
            }
        }

        final class ExistsCB implements Callback<Deferred<Boolean>, ArrayList<KeyValue>>{

            @Override
            public Deferred<Boolean> call(ArrayList<KeyValue> row) throws Exception {
                if(row == null){
                    return new CreateNewCB().call(null);
                }
                return Deferred.fromResult(true);
            }
        }

        return tsdb.getClient().get(get).addCallbackDeferring(new ExistsCB());
    }
}
